const METHOD={
  GET:'GET',
  POST:'POST',
  PUT:'PUT',
  DELETE:'DELETE'
}

const CONTENTTYPE={
  FORM:'application/x-www-form-urlencoded',
  JSON:'application/json'
}

class Request{
  _header={
    token:null,
  }
  _baseUrl ="http://127.0.0.1/"

  interceptors = []

  constructor(){
    const token=wx.getStorageSync('token')
    if(token){
      this._header.token=token
    }
  }

  intercept(res){
    return this.interceptors
                  .filter(f=> typeof f === 'function')
                  .every(f=> f(res))
  }

  request({url,method,data,json,header={}}){
    return new Promise((resolve,reject)=>{
      wx.request({
        url: (this._baseUrl || '')+url,
        method: method || METHOD.GET,
        data: data,
        header: {
           ...this._header,
           ...header,
          'content-type':json?'application/json':'application/x-www-form-urlencoded'
        },
        success: res=>{
          if(res.data.code==0){
            resolve(res.data.msg)
          }else{
            wx.showToast({
              title: '系统异常!',
              icon: 'none',
              duration: 3000
            })
          }
        },
        fail:reject
      })
    })
  }

  get(url,data,header,json){
    return this.request({url,method:METHOD.GET,data,json,header})
  }
  post(url,data,json,header){
    return this.request({url,method:METHOD.POST,data,json,header})
  }
  put(url,data,header,json){
    return this.request({url,method:METHOD.PUT,data,json,header})
  }
  delete(url,data,header,json){
    return this.request({url,method:METHOD.DELETE,data,json,header})
  }

  token(token){
    this._header.token=token
    return this
  }
  header(header){
    this._header=header
    return this
  }
  baseUrl(baseUrl){
    this._baseUrl=baseUrl
    return this
  }
  interceptor(f){
    if(typeof f === 'function'){
      this.interceptors.push(f)
    }
    return this
  }
}
export default new Request
export {METHOD}
export {CONTENTTYPE}